<template>
	<view class="">
		<view class="search">
			<view class="hd"><image src="/static/images/icon/search.png"></image></view>
			<view class="bd"><input @input="search" :value="searchValue" placeholder="搜索" /></view>
			<view v-if="searchValue != ''" @tap="clear" class="ft"><image src="/static/images/icon/delete.png"></image></view>
		</view>

		<index-list @click="itemClick" :empty-show="emptyShow" :top="100" :list-data="listData" color="#3F82FD" />
	</view>
</template>

<script>
const app = getApp()
const { CityList } = require('@/utils/city.js')

import IndexList from '@/components/index-list/index'

export default {
	components: {
		'index-list': IndexList
	},
	data() {
		return {
			listData: [],
			searchValue: '',
			emptyShow: false
		}
	},
	onLoad(query) {
		// 模拟异步获取数据场景
		setTimeout(() => {
			this.setList(this.formatList(CityList))
		}, 1000)
	},
	methods: {
		formatList(list) {
			let tempArr = []

			;['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'W', 'X', 'Y', 'Z'].forEach(initial => {
				let tempObj = {}

				tempObj.key = initial
				tempObj.data = list
					.filter(item => item.initial == initial)
					.map(item => {
						return { name: item.city, code: item.code, short: item.short }
					})
				//"id":"35","provincecode":"150000","city":"阿拉善盟","code":"152900","initial":"A","short":"Alashanmeng"

				if (tempObj.data && tempObj.data.length > 0) {
					tempArr.push(tempObj)
				}
			})

			return tempArr
		},
		search(e) {
			let value = e.detail.value
			this.searchValue = value

			let cityList = CityList.filter(item => item.city.indexOf(value) > -1 || item.short.indexOf(value) > -1)
			this.setList(this.formatList(cityList))
		},
		// searchConfirm(e) {
		// 	let value = e.detail.value
		// 	this.searchValue = value

		// 	let cityList = CityList.filter(item => item.city.indexOf(value) > -1 || item.short.indexOf(value) > -1)
		// 	this.setList(this.formatList(cityList))
		// },
		clear() {
			this.searchValue = ''
			this.setList(this.formatList(CityList))
		},
		setList(listData) {
			let emptyShow = listData.length == 0 ? true : false

			this.listData = listData
			this.emptyShow = emptyShow
		},
		itemClick(e) {
			console.log(e)
		}
	}
}
</script>

<style lang="scss">
@import '~@/common/css/variables';

page {
	padding-top: 100rpx;
}

.search {
	position: fixed;
	padding: 20rpx;
	background: #ffffff;
	top: 0;
	/* #ifdef H5 */
	top: var(--window-top);
	/* #endif */
	left: 0;
	right: 0;
	display: flex;
	align-items: center;
	.hd {
		font-size: 0;
		image {
			width: 36rpx;
			height: 36rpx;
			margin-right: 20rpx;
		}
	}
	.bd {
		flex: 1;
		input {
			width: 100%;
			height: 60rpx;
			border-radius: 10rpx;
			box-sizing: border-box;
		}
	}
	.ft {
		font-size: 0;
		padding: 30rpx;
		margin: -30rpx;
		image {
			width: 36rpx;
			height: 36rpx;
			margin-left: 20rpx;
		}
	}
}
</style>
